package io.gitee.yanbinchen;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author: alex
 * @since : 2025-03-04 19:35
 */
@Aspect
@Component
@Order(2)
public class SuperCacheAspect extends AbstractSuperCache{
    @Autowired
    SuperCacheService superCacheService;

    @Around("@annotation(io.gitee.yanbinchen.SuperKey)")
    public Object around(JoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SuperKey superKey = method.getAnnotation(SuperKey.class);
        String cacheKey = getCacheKey(superKey, method, joinPoint.getArgs());
        Object value = superCacheService.getCache(cacheKey, superKey.clzName(), superKey);
        if (StrUtils.isNotEmpty(value)) {
            return value;
        }
        Object res = ((ProceedingJoinPoint)joinPoint).proceed();
        if (StrUtils.isNotEmpty(res)) {
            superCacheService.setCache(cacheKey, res, superKey);
        }
        return res;
    }
}
